const { join } = require('path')

const config = require('config')
const { DefaultNamingStrategy } = require('typeorm')
const { snakeCase } = require('typeorm/util/StringUtils')

class SnakeNamingStrategy extends DefaultNamingStrategy {
  tableName(className, customName) {
    return customName ? customName : snakeCase(className)
  }

  columnName(propertyName, customName, embeddedPrefixes) {
    return snakeCase(embeddedPrefixes.join('_')) + (customName ? customName : snakeCase(propertyName))
  }

  relationName(propertyName) {
    return snakeCase(propertyName)
  }

  joinColumnName(relationName, referencedColumnName) {
    return snakeCase(relationName + '_' + referencedColumnName)
  }

  joinTableName(firstTableName, secondTableName, firstPropertyName, _secondPropertyName) {
    return snakeCase(firstTableName + '_' + firstPropertyName.replace(/\./gi, '_') + '_' + secondTableName)
  }

  joinTableColumnName(tableName, propertyName, columnName) {
    return snakeCase(tableName + '_' + (columnName ? columnName : propertyName))
  }

  classTableInheritanceParentColumnName(parentTableName, parentTableIdPropertyName) {
    return snakeCase(parentTableName + '_' + parentTableIdPropertyName)
  }

  eagerJoinRelationAlias(alias, propertyPath) {
    return alias + '__' + propertyPath.replace('.', '_')
  }

  indexName(tableOrName, columns, where) {
    const name = super.indexName(tableOrName, columns, where)
    return name.toLowerCase()
  }
}

/**
 * @type {import('typeorm').ConnectionOptions}
 */
module.exports = {
  type: 'mysql',
  host: config.MYSQL.HOST,
  port: config.MYSQL.PORT,
  username: config.MYSQL.USERNAME,
  password: config.MYSQL.PASSWORD,
  database: config.MYSQL.DATABASE,
  entities: [join(__dirname, 'packages/server-common/**/*.entity.ts')],
  migrations: [join(__dirname, 'migration/*.ts')],
  migrationsRun: process.env.NODE_ENV === 'development',
  migrationsTableName: 'typeorm_migration_table',
  logging: process.env.LOG_DB ? 'all' : ['error'],
  cli: {
    migrationsDir: 'migration',
    entitiesDir: join(__dirname, 'models'),
  },
  namingStrategy: new SnakeNamingStrategy(),
}
